public class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

class Solution1 {



    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int key = 0;  // key 为后一位进位的根据
        int num = 0;  //总值

        ListNode headNode = null; // 创建新的节点存放值
        ListNode cur = null;


        while (l1 != null || l2 != null) {  //有一个不为空继续循环，若其中一个链表的位置为空，增加一个值为0的节点


            //如果key == 1，注意 + 1 之后 key - 1
            //如果加上进位1 之后 num >= 10,key += 1;
            //将l1.val + l2.val - 10 的结果添加到新的链表中，两链表节点更新
            if (l1 == null)
                l1 = new ListNode(0);
            if (l2 == null)
                l2 = new ListNode(0);


            if (key == 1) {
                num = l1.val + l2.val + 1;
                key -= 1;
            } else {
                num = l1.val + l2.val;
            }

            if (num >= 10) {
                key += 1;
                num %= 10;
            }


            //将值尾插到新的链表中
            if (headNode == null) {
                cur = headNode = new ListNode(num);
            } else {
                cur.next = new ListNode(num);
                cur = cur.next;
            }

            l1 = l1.next;
            l2 = l2.next;
        }

        if (key == 1) {
            cur.next = new ListNode(key);
            cur = cur.next;
        }
        return headNode;
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(9);
        l1.next = new ListNode(9);
        l1.next.next = new ListNode(9);
        l1.next.next.next = new ListNode(9);
        l1.next.next.next.next = new ListNode(9);
        l1.next.next.next.next.next = new ListNode(9);
        l1.next.next.next.next.next.next = new ListNode(9);

        ListNode l2 = new ListNode(9);
        l2.next = new ListNode(9);
        l2.next.next = new ListNode(9);
        l2.next.next.next = new ListNode(9);

        ListNode headnode = addTwoNumbers(l1, l2);
        while (headnode != null) {
            System.out.println(headnode.val);
            headnode = headnode.next;
        }

    }

}
